<template>
  <nav 
    class="scroll-navigation fixed top-0 left-0 right-0 z-50 transition-all duration-300"
    :class="[
      isScrolled ? 'bg-white shadow-lg' : 'bg-transparent',
      isVisible ? 'translate-y-0' : '-translate-y-full'
    ]"
    ref="navRef"
  >
    <div class="container mx-auto px-4">
      <div class="flex items-center justify-between h-16">
        <!-- Logo with animation -->
        <div class="logo-container flex items-center" ref="logoRef">
          <div class="medical-logo w-10 h-10 mr-3 relative" ref="logoIconRef">
            <div class="absolute inset-0 bg-gradient-to-br from-red-500 to-red-600 rounded-lg flex items-center justify-center">
              <div class="medical-cross-small">
                <div class="w-6 h-1 bg-white absolute top-1/2 left-1/2 transform -translate-x-1/2 -translate-y-1/2"></div>
                <div class="w-1 h-6 bg-white absolute top-1/2 left-1/2 transform -translate-x-1/2 -translate-y-1/2"></div>
              </div>
            </div>
          </div>
          <span 
            class="logo-text font-bold text-xl transition-colors duration-300"
            :class="isScrolled ? 'text-gray-800' : 'text-white'"
            ref="logoTextRef"
          >
            药品商城
          </span>
        </div>

        <!-- Navigation items with stagger animation -->
        <div class="nav-items hidden md:flex items-center space-x-8" ref="navItemsRef">
          <a 
            v-for="(item, index) in navItems" 
            :key="item.id"
            :href="item.href"
            class="nav-item relative px-3 py-2 rounded-md text-sm font-medium transition-all duration-300"
            :class="[
              isScrolled ? 'text-gray-600 hover:text-red-600' : 'text-white hover:text-red-200',
              activeItem === item.id ? 'active' : ''
            ]"
            @click.prevent="handleNavClick(item)"
            :ref="el => { if (el) navItemElements[index] = el as HTMLElement }"
          >
            {{ item.label }}
            <div class="nav-indicator absolute bottom-0 left-0 w-full h-0.5 bg-red-500 transform scale-x-0 transition-transform duration-300"></div>
          </a>
        </div>

        <!-- Mobile menu button -->
        <button 
          class="mobile-menu-btn md:hidden p-2 rounded-md transition-colors duration-300"
          :class="isScrolled ? 'text-gray-600 hover:text-red-600' : 'text-white hover:text-red-200'"
          @click="toggleMobileMenu"
          ref="mobileMenuBtnRef"
        >
          <div class="hamburger-lines w-6 h-6 relative">
            <span class="hamburger-line absolute w-full h-0.5 bg-current transition-all duration-300 transform" :class="{ 'rotate-45 top-2.5': mobileMenuOpen, 'top-1': !mobileMenuOpen }"></span>
            <span class="hamburger-line absolute w-full h-0.5 bg-current transition-all duration-300 top-2.5" :class="{ 'opacity-0': mobileMenuOpen }"></span>
            <span class="hamburger-line absolute w-full h-0.5 bg-current transition-all duration-300 transform" :class="{ '-rotate-45 top-2.5': mobileMenuOpen, 'top-4': !mobileMenuOpen }"></span>
          </div>
        </button>
      </div>

      <!-- Mobile menu -->
      <div 
        class="mobile-menu md:hidden overflow-hidden transition-all duration-300"
        :class="mobileMenuOpen ? 'max-h-96 opacity-100' : 'max-h-0 opacity-0'"
        ref="mobileMenuRef"
      >
        <div class="py-4 space-y-2">
          <a 
            v-for="(item, index) in navItems" 
            :key="`mobile-${item.id}`"
            :href="item.href"
            class="mobile-nav-item block px-4 py-2 text-gray-600 hover:text-red-600 hover:bg-red-50 rounded-md transition-colors duration-300"
            @click="handleMobileNavClick(item)"
            :ref="el => { if (el) mobileNavItemElements[index] = el as HTMLElement }"
          >
            {{ item.label }}
          </a>
        </div>
      </div>
    </div>
  </nav>
</template>

<script setup lang="ts">
import { ref, onMounted, onUnmounted, nextTick } from 'vue'
import { gsap } from 'gsap'
import { ScrollTrigger } from 'gsap/ScrollTrigger'

// Register GSAP plugins
gsap.registerPlugin(ScrollTrigger)

interface NavItem {
  id: string
  label: string
  href: string
}

interface Props {
  items?: NavItem[]
}

const props = withDefaults(defineProps<Props>(), {
  items: () => [
    { id: 'home', label: '首页', href: '#home' },
    { id: 'products', label: '商品', href: '#products' },
    { id: 'categories', label: '分类', href: '#categories' },
    { id: 'brands', label: '品牌', href: '#brands' },
    { id: 'about', label: '关于', href: '#about' },
    { id: 'contact', label: '联系', href: '#contact' }
  ]
})

// Template refs
const navRef = ref<HTMLElement | null>(null)
const logoRef = ref<HTMLElement | null>(null)
const logoIconRef = ref<HTMLElement | null>(null)
const logoTextRef = ref<HTMLElement | null>(null)
const navItemsRef = ref<HTMLElement | null>(null)
const mobileMenuBtnRef = ref<HTMLElement | null>(null)
const mobileMenuRef = ref<HTMLElement | null>(null)
const navItemElements = ref<HTMLElement[]>([])
const mobileNavItemElements = ref<HTMLElement[]>([])

// Reactive data
const navItems = ref<NavItem[]>(props.items)
const isScrolled = ref(false)
const isVisible = ref(true)
const activeItem = ref('')
const mobileMenuOpen = ref(false)

// Animation instances
let navAnimations: gsap.core.Timeline[] = []
let scrollTriggerInstance: ScrollTrigger | null = null
let lastScrollY = 0

function handleScroll() {
  const currentScrollY = window.scrollY
  
  // Update scroll state
  isScrolled.value = currentScrollY > 50
  
  // Hide/show nav based on scroll direction
  if (currentScrollY > lastScrollY && currentScrollY > 100) {
    // Scrolling down
    isVisible.value = false
  } else {
    // Scrolling up
    isVisible.value = true
  }
  
  lastScrollY = currentScrollY
}

function handleNavClick(item: NavItem) {
  activeItem.value = item.id
  
  // Smooth scroll to section
  const element = document.querySelector(item.href)
  if (element) {
    element.scrollIntoView({ behavior: 'smooth' })
  }
  
  // Animate the nav item
  const navElement = navItemElements.value.find(el => 
    el.textContent?.trim() === item.label
  )
  if (navElement) {
    gsap.to(navElement.querySelector('.nav-indicator'), {
      scaleX: 1,
      duration: 0.3,
      ease: "power2.out"
    })
    
    // Reset other indicators
    navItemElements.value.forEach(el => {
      if (el !== navElement) {
        gsap.to(el.querySelector('.nav-indicator'), {
          scaleX: 0,
          duration: 0.3,
          ease: "power2.out"
        })
      }
    })
  }
}

function handleMobileNavClick(item: NavItem) {
  handleNavClick(item)
  mobileMenuOpen.value = false
}

function toggleMobileMenu() {
  mobileMenuOpen.value = !mobileMenuOpen.value
  
  if (mobileMenuOpen.value) {
    // Animate mobile menu items in
    nextTick(() => {
      gsap.fromTo(mobileNavItemElements.value, {
        opacity: 0,
        x: -20
      }, {
        opacity: 1,
        x: 0,
        duration: 0.3,
        stagger: 0.1,
        ease: "power2.out"
      })
    })
  }
}

function setupAnimations() {
  if (!navRef.value) return

  // Initial nav entrance animation
  const entranceTimeline = gsap.timeline()
  
  // Logo animation
  if (logoRef.value) {
    entranceTimeline.from(logoIconRef.value, {
      scale: 0,
      rotation: -180,
      duration: 0.8,
      ease: "back.out(1.7)"
    })
    .from(logoTextRef.value, {
      opacity: 0,
      x: -20,
      duration: 0.6,
      ease: "power2.out"
    }, "-=0.4")
  }

  // Nav items stagger animation
  if (navItemElements.value.length > 0) {
    entranceTimeline.from(navItemElements.value, {
      opacity: 0,
      y: -20,
      duration: 0.5,
      stagger: 0.1,
      ease: "power2.out"
    }, "-=0.3")
  }

  // Mobile menu button
  if (mobileMenuBtnRef.value) {
    entranceTimeline.from(mobileMenuBtnRef.value, {
      opacity: 0,
      scale: 0.8,
      duration: 0.4,
      ease: "power2.out"
    }, "-=0.2")
  }

  navAnimations.push(entranceTimeline)

  // Setup scroll-triggered logo animation
  if (logoIconRef.value) {
    const logoAnimation = gsap.to(logoIconRef.value, {
      rotation: 360,
      duration: 1,
      ease: "power2.inOut",
      paused: true
    })

    ScrollTrigger.create({
      trigger: document.body,
      start: "top -100px",
      end: "bottom bottom",
      onUpdate: (self) => {
        if (self.isActive) {
          logoAnimation.progress(self.progress)
        }
      }
    })
  }
}

onMounted(() => {
  // Add scroll listener
  window.addEventListener('scroll', handleScroll, { passive: true })
  
  nextTick(() => {
    setupAnimations()
  })
})

onUnmounted(() => {
  // Remove scroll listener
  window.removeEventListener('scroll', handleScroll)
  
  // Cleanup animations
  navAnimations.forEach(anim => anim.kill())
  
  if (scrollTriggerInstance) {
    scrollTriggerInstance.kill()
  }
  
  // Kill all ScrollTriggers created by this component
  ScrollTrigger.getAll().forEach(trigger => trigger.kill())
})
</script>

<style scoped>
.scroll-navigation {
  backdrop-filter: blur(10px);
  -webkit-backdrop-filter: blur(10px);
}

.medical-cross-small {
  position: relative;
  width: 100%;
  height: 100%;
}

.nav-item.active .nav-indicator {
  transform: scaleX(1);
}

.nav-item:hover .nav-indicator {
  transform: scaleX(1);
}

.hamburger-lines {
  cursor: pointer;
}

.mobile-menu {
  background: rgba(255, 255, 255, 0.95);
  backdrop-filter: blur(10px);
  -webkit-backdrop-filter: blur(10px);
}

.mobile-nav-item:hover {
  transform: translateX(4px);
}

/* Enhanced hover effects */
.nav-item {
  position: relative;
  overflow: hidden;
}

.nav-item::before {
  content: '';
  position: absolute;
  top: 0;
  left: -100%;
  width: 100%;
  height: 100%;
  background: linear-gradient(90deg, transparent, rgba(239, 68, 68, 0.1), transparent);
  transition: left 0.5s;
}

.nav-item:hover::before {
  left: 100%;
}

/* Logo pulse effect on scroll */
.medical-logo:hover .medical-cross-small {
  animation: pulse 1s infinite;
}

@keyframes pulse {
  0%, 100% { transform: scale(1); }
  50% { transform: scale(1.1); }
}

/* Responsive design */
@media (max-width: 768px) {
  .scroll-navigation {
    backdrop-filter: blur(8px);
    -webkit-backdrop-filter: blur(8px);
  }
}
</style> 
